package com.gaul.action;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class ActionServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取请求路径
		String path = getPath(req.getServletPath());
		
		//获取application作用域中map
		ServletContext context = req.getSession().getServletContext();
		Map<String, Action> xmlMap = (Map<String, Action>) context.getAttribute("xmlMap");

		Set<String> sets = xmlMap.keySet();
		System.out.println("++++++" + xmlMap==null);
		for(String s:sets){
			System.out.println(s+":"+xmlMap.get(s).toString());
		}
		System.out.println(path);
		Action action = xmlMap.get(path);
		String resultUrl = action.execute();
		dispatcher(resultUrl, req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		service(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		service(req, resp);
	}
	
	private String getPath(String path) {
		return path;
	}

	private void dispatcher(String url, HttpServletRequest req, HttpServletResponse resp) {
		try {
			req.getRequestDispatcher(url).forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
